package com.youpingou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youpingou.domain.*;
import com.youpingou.mapper.CategoryMapper;
import com.youpingou.mapper.ImpressionMapper;
import com.youpingou.mapper.SkuCommentMapper;
import com.youpingou.mapper.SkuMapper;
import com.youpingou.service.CategoryService;
import com.youpingou.service.SkuCommentService;
import com.youpingou.vo.CommentsResult;
import com.youpingou.vo.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
@Transactional
public class SkuCommentServiceImpl extends ServiceImpl<SkuCommentMapper, SkuComment> implements SkuCommentService {

    @Autowired
    private ImpressionMapper impressionMapper;

    @Autowired
    private SkuCommentMapper skuCommentMapper;

    @Autowired
    private SkuMapper skuMapper;

    /**
     * 在这个方法中，准备评论需要的数据
     *
     * @param skuId
     * @param pageRequest
     * @return
     */
    public CommentsResult findCommentsBySpuId(Integer skuId, PageRequest pageRequest){
        //1. 准备返回对象
        CommentsResult cr = new CommentsResult();
        //查找skuId
        Sku sku = skuMapper.selectById(skuId);
        Integer spuId = sku.getSpuId();

        //2. 准备印象
        List<Impression> impressionList = impressionMapper.findImpressionBySpuId(spuId);
        cr.setImpressions(impressionList);

        //3. 总评论数
        Integer count = skuCommentMapper.findCountBySpuId(spuId);
        cr.setComment_count(count);
        //4. 评论
        //4.1 分页
        List<SkuComment> list = skuCommentMapper.findCommentsBySpuId(spuId,pageRequest.getPage(),pageRequest.getPagesize());
        cr.setComments(list);

        //5. 获取好评
        Integer goods = 0;
        Integer common = 0;
        Integer bad = 0;

        for(SkuComment sc:list){
            if(sc.getRatio()==1){
                common++;
            }else if(sc.getRatio()==2){
                bad++;
            }
        }
        // 计算好评率、中评率、差评率
        Map<String,Integer> ratio = new HashMap<>();
        ratio.put("common",(common*100)/count);
        ratio.put("bad",(bad*100)/count);
        ratio.put("goods",100-ratio.get("common")-ratio.get("bad"));

        cr.setRatio(ratio);


        //10. 返回对象
        return cr;
    }
}